package com.lanou.zakerproject.base;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;

import com.android.volley.toolbox.ImageLoader;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * Created by dllo on 16/1/18.
 */
public class DiskCache implements ImageLoader.ImageCache {
    private String cacheDir = "";//指定路径

    //路径初始化
    public DiskCache() {
        //判断是否处于挂载状态
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //获取根路径
            File root = Environment.getExternalStorageDirectory();
            File cacheFile = new File(root.getAbsoluteFile() + "/cache");
            if (!cacheFile.exists()) {//如果文件路径存在
                cacheFile.mkdir();//创建路径
            }
            cacheDir = cacheFile.getAbsolutePath();
        }
    }

    @Override
    public Bitmap getBitmap(String url) {
        //判断，只有包含jpg或者png的才能截取
        if (!url.contains(".png") && !url.contains(".jpg")){
            return null;
        }
        //截取文件名
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);//4是.jpg的长度
        return BitmapFactory.decodeFile(cacheDir + "/" + url);
    }

    @Override
    public void putBitmap(String url, Bitmap bitmap) {
        if (!url.contains(".png") && !url.contains(".jpg")){
            return ;
        }
        url = url.substring(url.lastIndexOf("/"), url.lastIndexOf(".") + 4);//4是.jpg的长度
        FileOutputStream fos = null;
        try {
            fos = new FileOutputStream(cacheDir + "/" + url);
            bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);//把图片显入流
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } finally {
            if ((null != fos)) {
                try {
                    fos.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
